<?php
namespace App\Task;

use App\Job\InsertrugbyJob;
use Hyperf\DbConnection\Db;
use Hyperf\Logger\LoggerFactory;
use Hyperf\AsyncQueue\Driver\DriverFactory;
use Hyperf\Crontab\Annotation\Crontab;

/**
 * @Crontab(
 *     rule="0 0 1 1 *",
 *     name="AutoGetBlog",
 *     callback="execute",
 *     memo="每年1月1日执行一次"
 * )
 */
class AutoInsertrugby
{
    protected $logger;
    protected $queue;
    protected $loggerFactory;


    public function __construct(LoggerFactory $loggerFactory,DriverFactory $driverFactory)
    {
        $this->logger = $loggerFactory->get('tasklog', 'tasklog');
        $this->queue = $driverFactory->get('default');
        $this->loggerFactory = $loggerFactory;
    }

    public function execute()
    {
        try {
            $products = Db::table('products')
                ->select('id')
                ->where('status', 1)
                ->limit(30)
                ->get();
            if ($products->isNotEmpty()) {
                foreach ($products as $val){
                    $this->queue->push(new InsertrugbyJob($val->id));
                }
            }else{
                $this->logger->info("没有商品数据处理", []);
            }
        } catch (\InvalidArgumentException $e) {
            $this->logger->error("数据库配置错误", [
                'message' => $e->getMessage(),
                'trace' => $e->getTraceAsString(),
            ]);
        } catch (\PDOException $e) {
            $this->logger->error("数据库连接失败", [
                'message' => $e->getMessage(),
                'trace' => $e->getTraceAsString(),
            ]);
        } catch (\Throwable $e) {
            $this->logger->error("系统错误", [
                'message' => $e->getMessage(),
                'trace' => $e->getTraceAsString(),
            ]);
        }
    }
}
